package com.bookstore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bookstore.entity.User;
import com.bookstore.mapper.UserMapper;
import com.bookstore.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public boolean register(User user) {
        // 检查用户名是否已存在
        if (lambdaQuery().eq(User::getUsername, user.getUsername()).count() > 0) {
            throw new IllegalArgumentException("用户名已存在");
        }
        // 检查邮箱是否已存在
        if (lambdaQuery().eq(User::getEmail, user.getEmail()).count() > 0) {
            throw new IllegalArgumentException("邮箱已存在");
        }
        // 密码加密
        user.setPassword(encryptPassword(user.getPassword()));
        return save(user);
    }

    @Override
    public User login(String username, String password) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username)
                .eq(User::getPassword, encryptPassword(password));
        return getOne(queryWrapper);
    }

    @Override
    public boolean changePassword(Integer userId, String oldPassword, String newPassword) {
        User user = getById(userId);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        if (!user.getPassword().equals(encryptPassword(oldPassword))) {
            throw new IllegalArgumentException("原密码错误");
        }
        user.setPassword(encryptPassword(newPassword));
        return updateById(user);
    }

    @Override
    public boolean updateUserInfo(User user) {
        // 不允许修改用户名和密码
        user.setUsername(null);
        user.setPassword(null);
        return updateById(user);
    }

    private String encryptPassword(String password) {
        return DigestUtils.md5DigestAsHex(password.getBytes());
    }
} 